package xy001.imageloader_weichat;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.LruCache;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by xiangyang on 15/11/11.
 */
public class ImageLoader {

    private static ImageLoader mImageLoader;
    /**
     * 图片缓存的核心对象
     */
    private LruCache<String, Bitmap> mLruCache;
    /**
     * 线程池
     */
    private ExecutorService mThreadPool;
    /**
     * 默认线程数
     */
    private static final int DRAFULT_THREAD_COUNT = 1;
    /**
     *进栈模式
     */
    private Type mType = Type.LIFO;

    /**
     * 模式枚举
     */
    public enum Type {
        FIFI, LIFO;
    }

    /**
     * 任务队列
     */
    private LinkedList<Runnable> mTaskQueue;

    /**
     * 后台轮训线程
     */
    private Thread mPoolThread;
    private Handler mPoolThreadHandler;
    /**
     * UI线程中的Handleer;
     */
    private Handler mHander;
    /**
     * 同步唤醒问题，想当与notify and wait
     */
    private Semaphore mSemaphoremPoolThreadHandler=new Semaphore(0);
    private Semaphore mSemaphoeeThreadPool;

    /**
     * 单例模式，
     * @param threadCount
     * @param type
     */
    private ImageLoader(int threadCount, Type type) {
        init(threadCount, type);
    }

    /**
     * 初始化各种成员变量
     * @param threadCount  线程数
     * @param type 近栈类型
     */
    private void init(int threadCount, Type type) {
        mPoolThread = new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                mPoolThreadHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        //线程池取出任务执行
                        mThreadPool.execute(getTask());
                        try {
                            mSemaphoeeThreadPool.acquire();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }


                    }
                };
                mSemaphoremPoolThreadHandler.release();
                Looper.loop();
            }
        };
        mPoolThread.start();
        //获得最大的运行内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        //计算缓存内存
        int chcheMemory = maxMemory / 8;

        mLruCache = new LruCache<String, Bitmap>(chcheMemory) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight();
            }
        };
        /**
         * 创建线程池
         */
        mThreadPool = Executors.newFixedThreadPool(threadCount);
        mTaskQueue = new LinkedList<Runnable>();
        mType = type;

        mSemaphoeeThreadPool=new Semaphore(threadCount);
    }

    /**
     * @return
     */
    private Runnable getTask() {
        if (mType == Type.FIFI) {
            return mTaskQueue.removeFirst();
        } else if (mType == Type.LIFO) {
            return mTaskQueue.removeLast();
        }
        return null;
    }

    public static ImageLoader getInstance(int threadCount,Type type) {

        if (mImageLoader == null) {
            synchronized (ImageLoader.class) {
                if (mImageLoader == null) {
                    mImageLoader = new ImageLoader(threadCount, type);
                }
            }
        }


        return mImageLoader;

    }

    public void loadImage(final String path, final ImageView imageView) {
        imageView.setTag(path);
        if (mHander == null) {
            mHander = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    //获取图片，为imageView回调设置图片
                    ImageBeanHolder holder = (ImageBeanHolder) msg.obj;
                    Bitmap bm = holder.bitmap;
                    ImageView imageView = holder.imageView;
                    String path = holder.path;
                    if (imageView.getTag().toString().equals(path)) {
                        imageView.setImageBitmap(bm);
                    }
                }
            };

        }

        Bitmap bm = gitBitmapFromLruCache(path);
        if (bm != null) {
            refreashBitmap(bm, path, imageView);
        } else {
            addTask(new Runnable() {
                @Override
                public void run() {
//加载图片

                    //需要显示的大小
                    ImageSize imageSize = getImageViewSize(imageView);

                    //图片的压缩
                    Bitmap bm = decodeSampleBitmapFromPath(path, imageSize.width, imageSize.height);
                    //把图片加入到缓存
                    addBitmapToCache(path, bm);
                    refreashBitmap(bm, path, imageView);

                    mSemaphoeeThreadPool.release();

                }
            });
        }
    }

    private void refreashBitmap(Bitmap bm, String path, ImageView imageView) {
        Message message = Message.obtain();
        ImageBeanHolder holder = new ImageBeanHolder();
        holder.bitmap = bm;
        holder.path = path;
        holder.imageView = imageView;
        message.obj = holder;
        mHander.sendMessage(message);
    }

    /**
     * 将图片加入缓存
     *
     * @param path
     * @param bm
     */
    private void addBitmapToCache(String path, Bitmap bm) {

        if (gitBitmapFromLruCache(path) == null) {
            if (bm != null) {
                mLruCache.put(path, bm);
            }
        }
    }

    /**
     * 根据图片需要显示的宽和高对图片进行压缩
     *
     * @param path
     * @param width
     * @param height
     * @return
     */
    private Bitmap decodeSampleBitmapFromPath(String path, int width, int height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        options.inSampleSize = caculateInSampleSize(options, width, height);

        //使用计算的值再次解析图片

        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        return bitmap;
    }

    /**
     * 根据需求的宽和高和图片实际的宽和高计算SampleSize
     *
     * @param options
     * @param width
     * @param height
     * @return
     */
    private int caculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int width = options.outWidth;
        int height = options.outHeight;
        int inSampleSize = 1;

        if (width > reqWidth || height > reqHeight) {
            int widthRadio = Math.round(width * 1.0f / reqWidth);
            int heightRadio = Math.round(height * 1.0F / reqHeight);

            inSampleSize = Math.min(widthRadio, heightRadio);
        }

        return inSampleSize;
    }


    @SuppressLint("NewApi")
    private ImageSize getImageViewSize(ImageView imageView) {
        ImageSize imageSize = new ImageSize();
        DisplayMetrics displayMetric = imageView.getContext().getResources().getDisplayMetrics();
        ViewGroup.LayoutParams lp = imageView.getLayoutParams();
        int width = imageView.getWidth();
        if (width <= 0) {
            width = lp.width;
        }
        if (width <= 0) {
            width = getImageViewFieldValue(imageView,"mMaxWidth");
        }
        if (width <= 0) {
            width = displayMetric.widthPixels;
        }
        int height = imageView.getHeight();
        if (height <= 0) {
            height = lp.height;
        }
        if (height <= 0) {
            height = getImageViewFieldValue(imageView,"mMaxHeight");
        }
        if (height <= 0) {
            height = displayMetric.heightPixels;
        }
        imageSize.width = width;
        imageSize.height = height;
        return imageSize;
    }

    private static int getImageViewFieldValue(Object object,String fieldName)
    {
        int value=0;


        try {
            Field field=ImageView.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            int fieldValue=field.getInt(object);

            if (fieldValue>0&&fieldValue<Integer.MAX_VALUE)
            {
                value=fieldValue;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return  value;
    }
    private synchronized void addTask(Runnable runnable) {
        mTaskQueue.add(runnable);

        try {
            if (mPoolThreadHandler==null)
            mSemaphoremPoolThreadHandler.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        mPoolThreadHandler.sendEmptyMessage(0x110);

    }

    /**
     * @param path
     * @return
     */
    private Bitmap gitBitmapFromLruCache(String path) {
        return mLruCache.get(path);
    }


    private class ImageSize {
        int width;
        int height;

    }

    private class ImageBeanHolder {
        Bitmap bitmap;
        ImageView imageView;
        String path;
    }
}